//
//  MyWindowView.m
//  jRSSReader
//
//  Created by Jodynek on 4/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MyWindowView.h"
#import "ParsedFeed.h"

@implementation MyWindowView

- (void) refreshStories:(GoogleReader *) _gr
{ 
  // default feed width
  iFeedWidth  = 300;
  // position in feed (which feeds are visible)
  [self createTrackingArea];
  gr = _gr;
  iFirstVisibleFeed = 0;
  NSLog(@"News count: ... %d", (int)[[gr getStories] count]);
  [self setNeedsDisplay:TRUE];
}

- (void) shiftFeeds
{
  // repaint window
  [self setNeedsDisplay:YES];
  [self setFirstVisibleFeed];
}

- (void) setFirstVisibleFeed
{
  NSRect bounds = [self bounds];
  int iNumOfVisibleFeeds = bounds.size.width / iFeedWidth;
  if (iFirstVisibleFeed + iNumOfVisibleFeeds < [[gr getStories] count])
  {
    iFirstVisibleFeed = iFirstVisibleFeed + iNumOfVisibleFeeds;
  } else {
    iFirstVisibleFeed = 0;
  }
  //NSLog(@"Displaying Feed from %d", iFirstVisibleFeed);  
}

// Opens a URL in the default browser in background or foreground
- (void)openURL:(NSString *)url inBackground:(BOOL)background
{
  if (background)
  {
    NSArray* urls = [NSArray arrayWithObject:[NSURL URLWithString:url]];
    [[NSWorkspace sharedWorkspace] openURLs:urls withAppBundleIdentifier:nil options:NSWorkspaceLaunchWithoutActivation additionalEventParamDescriptor:nil launchIdentifiers:nil];    
  }
  else
  {
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];
  }
}

- (int)getSelectedFeed: (NSPoint) mouseLoc
{
  NSRect bounds = [self bounds];
  NSPoint mouseLocation = mouseLoc;
  if (bounds.size.height - 19 <= mouseLocation.y)
    return -1;
  
  int j = 0;
  int iNumOfFeeds = bounds.size.width / iFeedWidth;
  for (int i = iFirstVisibleFeed; i < iFirstVisibleFeed + iNumOfFeeds + 1; i++)
  {
    // check which feed was clicked
    if (mouseLocation.x > j*iFeedWidth && mouseLocation.x < (j+1)*iFeedWidth) 
    {
      if (i < [[gr getStories] count])
        return i;
      else 
        return -1;
    }
    j++;
  }
  return -1;
}

//
// mouse operations
//
- (void) createTrackingArea
{
  if (trackingArea != nil)
  {
    [self removeTrackingArea:trackingArea];    
  }
  int opts = (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingMouseMoved);
  trackingArea = [ [NSTrackingArea alloc] initWithRect:[self bounds]
                                               options:opts
                                                 owner:self
                                              userInfo:nil];
  [self addTrackingArea:trackingArea];
  
  NSPoint mouseLocation = [[self window] mouseLocationOutsideOfEventStream];
  mouseLocation = [self convertPoint: mouseLocation
                            fromView: nil];
  
  if (CGRectContainsPoint([self bounds], mouseLocation))
  {
    [self mouseEntered: nil];
  }
  else
  {
    [self mouseExited: nil];
  }
}

- (void)updateTrackingAreas 
{
  [self removeTrackingArea:trackingArea];
  [self createTrackingArea];
  [super updateTrackingAreas]; // Needed, according to the NSView documentation
}

- (void)mouseEntered:(NSEvent *)theEvent 
{
  iSelectedFeed = [self getSelectedFeed:[theEvent locationInWindow]];
  //[self displayIfNeeded];
}

- (void)mouseMoved:(NSEvent *)theEvent 
{
  iSelectedFeed = [self getSelectedFeed:[theEvent locationInWindow]];
  //NSLog(@"Selected feed: %d", [self getSelectedFeed:[theEvent locationInWindow]]);
  //[self displayIfNeeded];
  [self setNeedsDisplay:YES];
}

- (void)mouseExited:(NSEvent *)theEvent 
{
  [self setNeedsDisplayInRect:[self bounds]];
  iSelectedFeed = -1;
  [self displayIfNeeded];
}

- (void) mouseDown:(NSEvent *)theEvent
{
  NSRect bounds = [self bounds];
  NSPoint mouseLocation = [theEvent locationInWindow];
  //NSLog(@"X: %.0f Y: %.0f", mouseLocation.x, mouseLocation.y);
  // if we click on title bar exit
  if (bounds.size.height - 19 <= mouseLocation.y)
    return;
  // if we are resizing window, don't open RSS
  NSRect resizeRect;
  int iSizeOfResizeRect = 10;
  resizeRect.origin.x = bounds.size.width - iSizeOfResizeRect;
  resizeRect.origin.y = bounds.size.height - iSizeOfResizeRect;
  resizeRect.size.width = iSizeOfResizeRect;
  resizeRect.size.height = iSizeOfResizeRect;
  NSPoint mouseWindowLocation = mouseLocation;
  mouseWindowLocation.y = bounds.size.height - mouseLocation.y;
  if (NSPointInRect(mouseWindowLocation, resizeRect))
    return;
  
  int j = 0;
  int iNumOfFeeds = bounds.size.width / iFeedWidth;
  for (int i = iFirstVisibleFeed; i < iFirstVisibleFeed + iNumOfFeeds + 1; i++)
  {
    // check which feed was clicked
    if (mouseLocation.x > j*iFeedWidth && mouseLocation.x < (j+1)*iFeedWidth) 
    {
      ParsedFeed *pf = [[ParsedFeed alloc] init];
      pf = [[gr getStories] objectAtIndex:i];
      [self openURL:[pf link] inBackground:TRUE];      
      break;
    }
    j++;
  }
}

- (void)drawRect:(NSRect)dirtyRect
{
  NSRect bounds = [self bounds];
  bounds.size.height -= 19;
  NSBezierPath* clipShape = [NSBezierPath bezierPath];
  [clipShape appendBezierPathWithRoundedRect:bounds xRadius:4 yRadius:3];
  NSGradient* aGradient;
  aGradient = [[NSGradient alloc]
               initWithStartingColor:[NSColor blackColor] endingColor:[NSColor darkGrayColor]];
  
  [aGradient drawInBezierPath:clipShape angle:-90.0];  
  
  if ([[gr getStories] count] == 0) 
  {
    // draw feed title
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:20], 
                                NSFontAttributeName,[NSColor whiteColor], 
                                NSForegroundColorAttributeName, nil];    
<<<<<<< HEAD
    NSAttributedString * currentText=[[NSAttributedString alloc] initWithString:@"Please set internet connection or Google Reader account..." attributes: attributes];
=======
    NSAttributedString * currentText=[[NSAttributedString alloc] initWithString:@"Please set Google Reader account..." attributes: attributes];
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
    dirtyRect.origin.y = -30;
    dirtyRect.origin.x = 20;
    [currentText drawInRect: dirtyRect];     
  }
  else 
  {
    // size of canvas
    float titlebarHeight = 19.0;
    NSRect canvas = dirtyRect;
<<<<<<< HEAD
    canvas.size.height -= titlebarHeight;
    // size of one feed
    int iSpaceBetweenFeeds = 20;
=======
    canvas.size.height -= 19;
    // size of one feed
    int iSpaceBetweenFeeds = 10;
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
    int feedCount = (int)(canvas.size.width / iFeedWidth);
    int j = 0;
    for (int i = iFirstVisibleFeed; i < [[gr getStories] count]; i++)
    {
      if (i > [[gr getStories] count] || i > iFirstVisibleFeed + feedCount)
<<<<<<< HEAD
      {
//        iFirstVisibleFeed = 0;
        break;
      }
=======
        break;
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
      ParsedFeed *pf = [[ParsedFeed alloc] init];
      pf = [[gr getStories] objectAtIndex:i];
      //NSLog(@"Title - %@", [pf title]);
      
      if (i == iSelectedFeed && [pf feedRect].size.width > 0)
      {
        NSRect bounds = [pf feedRect];
<<<<<<< HEAD
        bounds.size.height -= titlebarHeight;
=======
        bounds.size.height -= 19;
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
        NSBezierPath* clipShape = [NSBezierPath bezierPath];
        [clipShape appendBezierPathWithRoundedRect:bounds xRadius:4 yRadius:3];
        NSGradient* aGradientInvert;
        aGradientInvert = [[NSGradient alloc]
                     initWithStartingColor:[NSColor darkGrayColor] endingColor:[NSColor blackColor]];
        [aGradientInvert drawInBezierPath:clipShape angle:-90.0];        
      }

      // draw info title
      NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
      [formatter setDateFormat:@"dd.MM.yyyy HH:mm"];
      NSString *stringFromDate = [formatter stringFromDate:[pf pubDate]];
      NSString *sSource = [pf source];
      sSource = [sSource stringByAppendingString:@" - "];                    
      NSString *sTitle;
      sTitle = [sSource stringByAppendingString:stringFromDate];
      
      NSDictionary *titleAttr = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:12], 
                                 NSFontAttributeName,[NSColor yellowColor], 
                                 NSForegroundColorAttributeName, nil];
      NSAttributedString * titleText=[[NSAttributedString alloc] initWithString:sTitle attributes: titleAttr];
<<<<<<< HEAD
      int iXPos = (j  * iFeedWidth) + iSpaceBetweenFeeds;
      NSRect feedRect;
      feedRect.size.width = iFeedWidth - iSpaceBetweenFeeds;
      feedRect.size.height = 12;
      feedRect.origin.x = iXPos;
      feedRect.origin.y = 40;
      [titleText drawInRect: feedRect]; 
      
      // draw line
      NSBezierPath *line = [NSBezierPath bezierPath];
      [[NSColor whiteColor] set];
      [NSBezierPath setDefaultLineWidth:.5f];
      NSPoint pFrom;
      pFrom.x = iXPos;
      pFrom.y = 36;
      NSPoint pTo;
      pTo.x = iXPos + iFeedWidth - iSpaceBetweenFeeds;
      pTo.y = 36;
      [line moveToPoint:pFrom];
      [line lineToPoint:pTo];
      [line stroke];
      
=======
      NSSize titleAttrSize = [titleText size];
      int iXPos = (j  * iFeedWidth) + iSpaceBetweenFeeds;
      NSRect feedRect;
      feedRect.size.width = iFeedWidth;
      feedRect.size.height = canvas.size.height;
      feedRect.origin.x = iXPos;
      feedRect.origin.y = 0;
      [titleText drawInRect: feedRect]; 
      
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
      // draw feed title
      NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:12], 
                                  NSFontAttributeName,[NSColor whiteColor], 
                                  NSForegroundColorAttributeName, nil];    
      NSAttributedString * currentText=[[NSAttributedString alloc] initWithString:[pf title] attributes: attributes];
<<<<<<< HEAD
      feedRect.size.width = iFeedWidth - iSpaceBetweenFeeds;
      feedRect.size.height = canvas.size.height;
      feedRect.origin.x = iXPos;
      feedRect.origin.y = -16;
=======
      NSSize attrSize = [currentText size];
      feedRect.size.width = iFeedWidth;
      feedRect.size.height = canvas.size.height;
      feedRect.origin.x = iXPos;
      feedRect.origin.y = -14;
>>>>>>> 42acf678065da260e0e994d7eaf924250eff120f
      [currentText drawInRect: feedRect]; 
      
      feedRect.origin.x = iXPos;
      feedRect.origin.y = 0;
      feedRect.size.height = 70;
      pf.feedRect = feedRect;    
      j++;
    }
  }
}

@end
